package com.spence.wsdemo.interceptor;

import com.spence.wsdemo.config.WebSocketConfig;
import com.spence.wsdemo.entity.WsPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

/**
 * @author spence_xu
 * @date 2020/5/20 14:15
 */
@Component
@Slf4j
public class WsHandshakeHandler extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        String userName = (String) servletRequest.getAttribute(WebSocketConfig.TOKEN_USER);
        if (StringUtils.isNotBlank(userName)) {
            return new WsPrincipal(userName);
        }
        return null;
    }
}
